<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { UploadOutlined } from '@ant-design/icons-vue';
import { Button, FormItem } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { saveDocumentTemplateFileApi } from '#/api';
import { FileUploader } from '#/components';

defineOptions({
  name: 'DocumentTemplateFileDrawer',
});
let fileDetailId: any;
const [Form, formApi] = useVbenForm({
  schema: [
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
        readonly: true,
      },
      fieldName: 'originalFilename',
      label: $t('document.documentTemplateFile.field.originalFilename'),
      rules: 'required',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'filename',
      label: $t('document.documentTemplateFile.field.filename'),
      rules: 'required',
      description: '',
    },
  ],
  showDefaultActions: false,
  handleSubmit: onSubmit,
});

const [Modal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    await formApi.submitForm();
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, disabled } = modalApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values);
      }
      const enableEdit = !!disabled;
      formApi.setState({ commonConfig: { disabled: enableEdit } });
      modalApi.setState({ showConfirmButton: !enableEdit });
    }
  },
  title: $t('document.documentTemplateFile.title'),
});

async function onSubmit(values: any) {
  const rawData = modalApi.getData().values;
  values.documentTemplateFileId = rawData.documentTemplateFileId;
  values.documentTemplateId = rawData.documentTemplateId;
  values.fileDetailId = fileDetailId;
  await saveDocumentTemplateFileApi(values);
  modalApi.setData({ success: true });
}

function uploadChange(param: any) {
  const file = param.file;
  if (file.status === 'done') {
    formApi.setFieldValue('originalFilename', file.name);
    fileDetailId = file.response.id;
  }
}
</script>
<template>
  <Modal class="w-[600px]">
    <Form>
      <FormItem
        :label="$t('common.upload')"
        :label-col="{ span: 4 }"
        label-align="right"
      >
        <FileUploader
          :show-upload-list="false"
          class="mr-2"
          @change="uploadChange"
        >
          <Button><UploadOutlined />{{ $t('common.upload') }}</Button>
        </FileUploader>
      </FormItem>
    </Form>
  </Modal>
</template>
